package com.linghang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linghang.demo.domain.Inform;
import com.linghang.demo.domain.InformExample;
import com.linghang.demo.mapper.InformMapper;
import com.linghang.demo.req.InformQueryReq;
import com.linghang.demo.req.InformSaveReq;
import com.linghang.demo.resp.InformQueryResp;
import com.linghang.demo.resp.PageResp;
import com.linghang.demo.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class InformService {
    private int id=10;
    @Resource
    private InformMapper informMapper;
    private static final Logger LOG = LoggerFactory.getLogger(InformService.class);

    public List<Inform> list(){
        return informMapper.selectByExample(null);
    }

    public PageResp<InformQueryResp> list(InformQueryReq req) {
        InformExample informExample = new InformExample();
        InformExample.Criteria criteria = informExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getId())) {
            criteria.andIdEqualTo(  req.getId() );
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Inform> informList = informMapper.selectByExample(informExample);

        PageInfo<Inform> pageInfo = new PageInfo<>(informList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // List<InformResp> respList = new ArrayList<>();
        // for (Inform inform : informList) {
        //     // InformResp informResp = new InformResp();
        //     // BeanUtils.copyProperties(inform, informResp);
        //     // 对象复制
        //     InformResp informResp = CopyUtil.copy(inform, InformResp.class);
        //
        //     respList.add(informResp);
        // }

        // 列表复制
        List<InformQueryResp> list = CopyUtil.copyList(informList, InformQueryResp.class);

        PageResp<InformQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     */
    public void save(InformSaveReq req) {
        Inform inform= CopyUtil.copy(req, Inform.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            inform.setId(id++);
            informMapper.insert(inform);

        } else {
            // 更新
            informMapper.updateByPrimaryKey(inform);

        }
    }

    
    public void  delete(int id){
        informMapper.deleteByPrimaryKey(id);
    }
}
